<template>
  <div class="question-edit-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <i class="fas fa-edit"></i>
          编辑题目
        </h1>
        <p class="page-subtitle">修改和更新您的编程题目</p>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="content-wrapper">
      <form @submit.prevent="updateQuestion" class="question-form">
        <!-- 基础信息卡片 -->
        <div class="form-card">
          <div class="card-header">
            <h3><i class="fas fa-info-circle"></i> 基础信息</h3>
          </div>
          <div class="card-content">
            <div class="form-row">
              <div class="form-group">
                <label for="questionName">题目名称 <span class="required">*</span></label>
                <input 
                  type="text" 
                  id="questionName"
                  v-model="formData.questionName"
                  placeholder="请输入题目名称，如：两数之和"
                  required
                >
              </div>
              <div class="form-group">
                <label for="courseLevelId">课程等级 <span class="required">*</span></label>
                <select id="courseLevelId" v-model="formData.courseLevelId" required>
                  <option value="">请选择课程等级</option>
                  <option value="1001">初级</option>
                  <option value="2001">中级</option>
                  <option value="3001">高级</option>
                  <option value="5001">专家级</option>
                </select>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="questionType">题目类型 <span class="required">*</span></label>
                <select id="questionType" v-model="formData.questionType" required>
                  <option value="">请选择题目类型</option>
                  <option value="1">算法题</option>
                  <option value="2">数据结构</option>
                  <option value="3">动态规划</option>
                  <option value="4">图论</option>
                  <option value="5">字符串处理</option>
                  <option value="6">数学计算</option>
                  <option value="7">数组操作</option>
                </select>
              </div>
              <div class="form-group">
                <label for="difficulty">难度等级 <span class="required">*</span></label>
                <select id="difficulty" v-model="formData.difficulty" required>
                  <option value="">请选择难度</option>
                  <option value="1">难度 1</option>
                  <option value="2">难度 2</option>
                  <option value="3">难度 3</option>
                  <option value="4">难度 4</option>
                  <option value="5">难度 5</option>
                  <option value="6">难度 6</option>
                </select>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="label">标签</label>
                <input 
                  type="text" 
                  id="label"
                  v-model="formData.label"
                  placeholder="如：数组,哈希表"
                >
              </div>
              <div class="form-group">
                <label for="isPublic">是否公开</label>
                <select id="isPublic" v-model="formData.isPublic">
                  <option value="1">公开</option>
                  <option value="0">私有</option>
                </select>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="strict">是否使用严格判题</label>
                <div class="checkbox-wrapper">
                  <input 
                    type="checkbox" 
                    id="strict"
                    v-model="formData.strict"
                    true-value="1"
                    false-value="0"
                    checked
                    disabled
                  >
                  <label for="strict" class="checkbox-label">严格判题（固定使用）</label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 题目描述卡片 -->
        <div class="form-card">
          <div class="card-header">
            <h3><i class="fas fa-edit"></i> 题目描述</h3>
          </div>
          <div class="card-content">
            <div class="form-group full-width">
              <label for="questionDescribe">题目描述（文字）<span class="optional-tag">（选填）</span></label>
              <textarea 
                id="questionDescribe"
                v-model="formData.questionDescribe"
                placeholder="请详细描述题目要求，包括问题背景、输入输出要求等"
                rows="6"
              ></textarea>
            </div>
            
            <!-- 🔥 题目描述图片上传 -->
            <div class="form-group full-width">
              <label for="questionDescribePicture">题目描述（图片）<span class="optional-tag">（选填）</span></label>
              
              <!-- 显示当前图片（如果有） -->
              <div v-if="formData.questionDescribePicture && isImageUrl(formData.questionDescribePicture) && !uploadingDescribeImage" class="current-describe-image">
                <p class="image-label">当前题目描述图片：</p>
                <img :src="getImageUrl(formData.questionDescribePicture)" alt="当前题目描述图片" class="preview-image-small">
                <small class="form-hint">点击下方区域可以更换图片</small>
              </div>
              
              <div class="test-case-file-upload-area" @click="triggerDescribeImageInput">
                <input 
                  ref="describeImageInput"
                  type="file" 
                  @change="handleDescribeImageUpload"
                  accept="image/*"
                  style="display: none"
                >
                <div v-if="uploadingDescribeImage" class="uploading-state">
                  <i class="fas fa-spinner fa-spin"></i>
                  <p>上传中...</p>
                </div>
                <div v-else class="upload-placeholder-small">
                  <i class="fas fa-image"></i>
                  <p>{{ formData.questionDescribePicture ? '点击更换题目描述图片' : '点击上传题目描述图片' }}</p>
                  <small>支持 JPG、PNG、GIF</small>
                </div>
              </div>
              <div v-if="formData.questionDescribePicture && isImageUrl(formData.questionDescribePicture)" class="upload-success-hint">
                <i class="fas fa-check"></i>
                <span>图片已设置</span>
              </div>
            </div>

            <div class="form-group full-width">
              <label>题目图片</label>
              
              <!-- 图片上传方式选择 -->
              <div class="image-upload-options">
                <div class="upload-option">
                  <input 
                    type="radio" 
                    id="uploadTypeUrl" 
                    name="uploadType" 
                    value="url" 
                    v-model="uploadType"
                  >
                  <label for="uploadTypeUrl">远程图片URL</label>
                </div>
                <div class="upload-option">
                  <input 
                    type="radio" 
                    id="uploadTypeFile" 
                    name="uploadType" 
                    value="file" 
                    v-model="uploadType"
                  >
                  <label for="uploadTypeFile">上传本地图片</label>
                </div>
              </div>

              <!-- 远程URL输入 -->
              <div v-if="uploadType === 'url'" class="upload-section">
                <input 
                  type="url" 
                  id="questionPicture"
                  v-model="formData.questionPicture"
                  placeholder="https://example.com/images/q1.png"
                >
                <small class="form-hint">输入图片的完整URL地址</small>
              </div>

              <!-- 本地文件上传 -->
              <div v-if="uploadType === 'file'" class="upload-section">
                <!-- 已有图片预览（编辑时显示） -->
                <div v-if="formData.questionPicture && !selectedFile" class="current-image">
                  <p class="image-label">当前题目图片：</p>
                  <img :src="getImageUrl(formData.questionPicture)" alt="当前题目图片" class="preview-image" @error="onImageError">
                  <small class="form-hint">点击下方区域可以更换图片</small>
                </div>
                
                <div class="file-upload-area" @click="triggerFileInput" @dragover.prevent @drop.prevent="handleFileDrop">
                  <input 
                    ref="fileInput" 
                    type="file" 
                    accept="image/*" 
                    @change="handleFileSelect" 
                    style="display: none"
                  >
                  <div v-if="!selectedFile && !uploadedImageUrl" class="upload-placeholder">
                    <i class="fas fa-cloud-upload-alt"></i>
                    <p>{{ formData.questionPicture ? '点击更换图片' : '点击选择图片或拖拽图片到此处' }}</p>
                    <small>支持 JPG、PNG、GIF 格式，大小不超过 5MB</small>
                  </div>
                  <div v-if="selectedFile" class="file-info">
                    <i class="fas fa-image"></i>
                    <span>{{ selectedFile.name }}</span>
                    <button type="button" @click.stop="clearFile" class="clear-btn">
                      <i class="fas fa-times"></i>
                    </button>
                  </div>
                </div>
                
                <small class="form-hint">{{ selectedFile ? '选择图片文件后，在保存题目时会一并上传' : (formData.questionPicture ? '如需更换图片，请点击上方区域选择新图片' : '选择图片文件后，在保存题目时会一并上传') }}</small>
              </div>

              <!-- 图片预览（URL方式） -->
              <div v-if="uploadType === 'url' && formData.questionPicture" class="image-preview">
                <img :src="formData.questionPicture" alt="图片预览" class="preview-image" @error="onImageError">
              </div>

              <!-- 当前图片预览（编辑时显示已有图片） -->
              <div v-if="formData.questionPicture && uploadType === 'url'" class="current-image">
                <p class="image-label">当前图片：</p>
                <img :src="getImageUrl(formData.questionPicture)" alt="当前题目图片" class="preview-image" @error="onImageError">
              </div>
            </div>
          </div>
        </div>

        <!-- 测试用例卡片 -->
        <div class="form-card">
          <div class="card-header">
            <h3><i class="fas fa-list-alt"></i> 测试用例</h3>
          </div>
          <div class="card-content">
            <!-- 输入格式 -->
            <div class="form-group full-width">
              <label for="inputFormat">输入格式</label>
              <textarea 
                id="inputFormat"
                v-model="formData.inputFormat"
                placeholder="描述输入数据的格式，如：第一行输入两个整数 n 和 target，第二行输入 n 个整数"
                rows="2"
              ></textarea>
            </div>
            
            <!-- 输出格式 -->
            <div class="form-group full-width">
              <label for="outputFormat">输出格式</label>
              
              <!-- 输出格式类型选择 -->
              <div class="output-type-selector">
                <label class="radio-label">
                  <input 
                    type="radio" 
                    v-model="formData.outputType" 
                    value="text"
                  >
                  <span>文本描述</span>
                </label>
                <label class="radio-label">
                  <input 
                    type="radio" 
                    v-model="formData.outputType" 
                    value="local"
                  >
                  <span>上传图片</span>
                </label>
              </div>
              
              <!-- 文本格式输出 -->
              <textarea 
                v-if="formData.outputType === 'text'"
                id="outputFormat"
                v-model="formData.outputFormat"
                placeholder="如：输出一行，包含两个数字，表示满足条件的两个数的下标"
                rows="2"
              ></textarea>
              
              <!-- 图片格式输出 -->
              <div v-else-if="formData.outputType === 'local'" class="output-section">
                <!-- 显示当前图片（如果有） -->
                <div v-if="formData.outputFormat && isImageUrl(formData.outputFormat) && !uploadingOutputImage" class="current-output-image">
                  <p class="image-label">当前输出格式图片：</p>
                  <img :src="getImageUrl(formData.outputFormat)" alt="当前输出格式图片" class="preview-image-small">
                  <small class="form-hint">点击下方区域可以更换图片</small>
                </div>
                
                <div class="test-case-file-upload-area" @click="triggerOutputImageInput">
                  <input 
                    ref="outputImageInput"
                    type="file" 
                    @change="handleOutputImageUpload"
                    accept="image/*"
                    style="display: none"
                  >
                  <div v-if="uploadingOutputImage" class="uploading-state">
                    <i class="fas fa-spinner fa-spin"></i>
                    <p>上传中...</p>
                  </div>
                  <div v-else class="upload-placeholder-small">
                    <i class="fas fa-image"></i>
                    <p>{{ formData.outputFormat ? '点击更换输出格式图片' : '点击上传输出格式图片' }}</p>
                    <small>支持 JPG、PNG、GIF</small>
                  </div>
                </div>
                <div v-if="formData.outputFormat && isImageUrl(formData.outputFormat)" class="upload-success-hint">
                  <i class="fas fa-check"></i>
                  <span>图片已设置</span>
                </div>
              </div>
            </div>
            
            <!-- 数据范围和提示 -->
            <div class="form-group full-width">
              <label for="rangeAndPrompt">数据范围和提示 <span class="required">*</span></label>
              <textarea 
                id="rangeAndPrompt"
                v-model="formData.rangeAndPrompt"
                placeholder="如：1 <= n <= 10^4&#10;-10^9 <= nums[i] <= 10^9&#10;-10^9 <= target <= 10^9"
                rows="3"
                required
              ></textarea>
            </div>
            
            <!-- 测试用例 - 多组输入输出 -->
            <div class="form-group full-width">
              <div class="test-cases-header">
                <label>测试用例</label>
                <button type="button" @click="addTestCase" class="add-test-case-btn">
                  <i class="fas fa-plus"></i>
                  添加测试用例
                </button>
              </div>
              
              <div class="test-cases-list">
                <div v-if="testCases.length === 0" class="no-test-cases">
                  <i class="fas fa-info-circle"></i>
                  <p>暂无测试用例，点击上方按钮添加</p>
                </div>
                
                <div v-for="(testCase, index) in testCases" :key="index" class="test-case-item">
                  <div class="test-case-header">
                    <span class="test-case-number">测试用例 {{ index + 1 }}</span>
                    <button type="button" @click="removeTestCase(index)" class="remove-test-case-btn">
                      <i class="fas fa-trash"></i>
                      删除
                    </button>
                  </div>
                  
                  <div class="test-case-content">
                    <!-- 输入格式 -->
                    <div class="format-section">
                      <label>输入格式</label>
                      <textarea 
                        v-model="testCase.inputFormat"
                        placeholder="如：第一行输入两个整数 n 和 target，第二行输入 n 个整数"
                        rows="2"
                        class="test-case-format"
                      ></textarea>
                    </div>
                    
                    <!-- 输出格式 - 支持文本或图片 -->
                    <div class="format-section">
                      <label>输出格式</label>
                      
                      <!-- 输出格式类型选择 -->
                      <div class="output-type-options">
                        <div class="type-option">
                          <input 
                            type="radio" 
                            :id="'outputTypeText' + index" 
                            :name="'outputType' + index" 
                            value="text" 
                            v-model="testCase.outputType"
                          >
                          <label :for="'outputTypeText' + index">文本描述</label>
                        </div>
                        <div class="type-option">
                          <input 
                            type="radio" 
                            :id="'outputTypeImage' + index" 
                            :name="'outputType' + index" 
                            value="image" 
                            v-model="testCase.outputType"
                          >
                          <label :for="'outputTypeImage' + index">上传图片</label>
                        </div>
                      </div>

                      <!-- 文本输入 -->
                      <div v-if="testCase.outputType === 'text'" class="output-section">
                        <textarea 
                          v-model="testCase.outputFormat"
                          placeholder="如：输出一行，包含两个数字，表示满足条件的两个数的下标"
                          rows="2"
                          class="test-case-format"
                        ></textarea>
                      </div>

                      <!-- 图片上传 -->
                      <div v-if="testCase.outputType === 'image'" class="output-section">
                        <!-- 显示已有的图片 -->
                        <div v-if="testCase.outputFilePath && !testCase.uploading" class="current-test-case-image">
                          <p class="image-label">当前输出格式图片：</p>
                          <div class="image-preview-container">
                            <img :src="getImageUrl(testCase.outputFilePath)" alt="输出格式图片" class="preview-image-medium">
                            <button type="button" @click="clearTestCaseOutputFile(index)" class="change-image-btn">
                              <i class="fas fa-sync-alt"></i>
                              更换图片
                            </button>
                          </div>
                          <small class="form-hint">点击下方区域可以更换图片</small>
                        </div>
                        
                        <div class="test-case-file-upload-area" @click="triggerTestCaseOutputFileInput(index)">
                          <input 
                            :ref="'testCaseOutputFileInput' + index" 
                            type="file" 
                            accept="image/*" 
                            @change="handleTestCaseOutputFileSelect($event, index)" 
                            style="display: none"
                          >
                          <div v-if="testCase.uploading" class="uploading-state">
                            <i class="fas fa-spinner fa-spin"></i>
                            <p>上传中...</p>
                          </div>
                          <div v-else-if="!testCase.outputFile && !testCase.outputFilePath" class="upload-placeholder-small">
                            <i class="fas fa-image"></i>
                            <p>点击上传图片</p>
                            <small>支持 JPG、PNG、GIF</small>
                          </div>
                          <div v-else-if="testCase.outputFile" class="file-info-small">
                            <i class="fas fa-check-circle"></i>
                            <span>{{ testCase.outputFile.name }}</span>
                            <button type="button" @click.stop="clearTestCaseOutputFile(index)" class="clear-btn-small">
                              <i class="fas fa-times"></i>
                            </button>
                          </div>
                          <div v-else class="upload-placeholder-small">
                            <i class="fas fa-sync-alt"></i>
                            <p>点击更换图片</p>
                            <small>支持 JPG、PNG、GIF</small>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="form-group full-width">
              <label>参考程序结果</label>
              <textarea 
                id="testCode"
                v-model="formData.testCode"
                placeholder="请输入题目的标准答案或解题思路"
                rows="4"
              ></textarea>
              <small class="form-hint">请提供题目的标准答案，这将帮助系统进行自动判题</small>
            </div>

            <!-- 测试数据 -->
            <div class="form-group full-width">
              <div class="test-cases-header">
                <label>测试数据</label>
                <button type="button" @click="addTestData" class="add-test-case-btn">
                  <i class="fas fa-plus"></i>
                  添加测试数据
                </button>
              </div>
              
              <div class="test-cases-list">
                <div v-if="testDataItems.length === 0" class="no-test-cases">
                  <i class="fas fa-info-circle"></i>
                  <p>暂无测试数据，点击上方按钮添加</p>
                </div>
                
                <div v-for="(testData, index) in testDataItems" :key="index" class="test-case-item">
                  <div class="test-case-header">
                    <span class="test-case-number">测试数据 {{ index + 1 }}</span>
                    <button type="button" @click="removeTestData(index)" class="remove-test-case-btn">
                      <i class="fas fa-trash"></i>
                      删除
                    </button>
                  </div>
                  
                  <div class="test-case-content">
                    <div class="format-section">
                      <textarea 
                        v-model="testData.content"
                        placeholder="请输入测试数据，如：3 9&#10;2 7 11 15"
                        rows="4"
                        class="test-case-format"
                      ></textarea>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 限制条件卡片 -->
        <div class="form-card">
          <div class="card-header">
            <h3><i class="fas fa-cog"></i> 限制条件</h3>
          </div>
          <div class="card-content">
            <div class="form-row">
              <div class="form-group">
                <label for="timeLimit">时间限制 (毫秒) <span class="required">*</span></label>
                <input 
                  type="number" 
                  id="timeLimit"
                  v-model.number="formData.timeLimit"
                  placeholder="1000"
                  min="100"
                  max="10000"
                  required
                >
                <small class="form-hint">建议范围：100-10000毫秒</small>
              </div>
              <div class="form-group">
                <label for="spaceLimitation">空间限制 (字节) <span class="required">*</span></label>
                <input 
                  type="number" 
                  id="spaceLimitation"
                  v-model.number="formData.spaceLimitation"
                  placeholder="268435456"
                  min="1048576"
                  required
                >
                <small class="form-hint">建议最小值：1MB (1048576字节)</small>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <button type="button" @click="goBack" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i>
            取消
          </button>
          <button type="button" @click="deleteQuestion" class="btn btn-danger" :disabled="isDeleting">
            <i class="fas fa-trash"></i>
            {{ isDeleting ? '删除中...' : '删除题目' }}
          </button>
          <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
            <i class="fas fa-save"></i>
            {{ isSubmitting ? '保存中...' : '保存修改' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
// import { getQuestionById } from '@/api/question'
import { getTestQuestionById, updateTestQuestion, deleteTestQuestion } from '@/api/testQuestion'
import { uploadFile } from '@/api/file'
import logger from '../utils/logger.js'

export default {
  name: 'QuestionEdit',
  data() {
    return {
      isSubmitting: false,
      isDeleting: false,
      isLoading: true,
      questionId: null,
      // 图片上传相关
      uploadType: 'url', // 'url' 或 'file'
      selectedFile: null,
      // 输出格式类型
      outputFormatType: '', // 不默认选择，让用户自己选择 'text' 或 'image'
      selectedOutputFile: null, // 输出格式图片文件
      uploadingOutputImage: false, // 全局输出格式图片上传状态
      uploadingDescribeImage: false, // 题目描述图片上传状态
      // 测试用例数组
      testCases: [],
      // 测试数据数组
      testDataItems: [],
      formData: {
        id: null,  // 题目ID
        createUserId: null,
        courseLevelId: '',
        questionName: '',
        questionType: '',
        isPublic: 1,
        strict: '0',  // 是否使用严格判题，默认不勾选，string类型
        timeLimit: 1000,
        spaceLimitation: 268435456,
        questionDescribe: '',
        questionDescribePicture: '', // 🔥 题目描述图片路径（string类型）
        questionPicture: '',
        inputFormat: '',
        outputFormat: '',
        rangeAndPrompt: '',
        testCases: '',  // 测试用例
        testCode: '',   // 答案代码
        testData: '',   // 测试数据
        difficulty: '',
        label: '',
        submissionQuantity: 0,
        byQuantity: 0
      }
    }
  },
  methods: {
    async loadQuestionData() {
      try {
        logger.log('📖 [QuestionEdit] 加载题目数据...');
        this.isLoading = true;
        
        // 优先使用API接口，失败时使用本地存储作为备用
        let questionData = null;
        
        try {
          logger.log('🌐 [QuestionEdit] 尝试从API加载题目数据...');
          logger.log('📡 [QuestionEdit] 调用接口: /goc/testQuestion/findById');
          logger.log('📋 [QuestionEdit] 题目ID:', this.questionId);
          
          const response = await getTestQuestionById(this.questionId);
          logger.log('🌐 [QuestionEdit] API响应:', response);
          logger.log('🌐 [QuestionEdit] API响应类型:', typeof response);
          logger.log('🌐 [QuestionEdit] API响应字段:', response ? Object.keys(response) : 'null');
          
          // 检查API响应格式：响应拦截器已经返回了 response.data，所以这里直接是 {code: 0, message: '操作成功', data: {...}}
          if (response && response.code === 0 && response.data) {
            questionData = response.data;
            logger.log('✅ [QuestionEdit] 成功获取题目数据:', questionData);
            logger.log('✅ [QuestionEdit] 题目数据字段:', Object.keys(questionData));
          } else {
            logger.warn('⚠️ [QuestionEdit] API响应格式异常:', response);
            throw new Error(`API错误: ${response?.message || '获取题目数据失败'}`);
          }
        } catch (apiError) {
          logger.warn('⚠️ [QuestionEdit] API加载失败，尝试本地存储:', apiError);
          
          // 备用方案：从本地存储加载题目数据
          const { default: localQuestionStorage } = await import('@/utils/localStorage');
          questionData = localQuestionStorage.getQuestionById(this.questionId);
          logger.log('📖 [QuestionEdit] 本地存储题目数据:', questionData);
        }
        
        if (questionData) {
          logger.log('📊 [QuestionEdit] 原始题目数据:', questionData);
          logger.log('📊 [QuestionEdit] 原始题目数据字段:', Object.keys(questionData));
          logger.log('🔍 [QuestionEdit] 调试用户ID精度问题:');
          logger.log('  - 后端返回的createUserId (原始):', questionData.createUserId);
          logger.log('  - createUserId类型:', typeof questionData.createUserId);
          logger.log('  - createUserId转字符串:', String(questionData.createUserId));
          logger.log('  - createUserId长度:', String(questionData.createUserId).length, '位');
          
          // 填充表单数据 - 映射后端字段到表单字段
          this.formData = {
            ...this.formData,
            // 基础字段映射
            id: questionData.id,
            questionName: questionData.questionName || '',
            questionDescribe: questionData.questionDescribe || '', // 注意字段名
            questionDescribePicture: questionData.questionDescribePicture || '', // 🔥 题目描述图片
            questionPicture: questionData.questionPicture || '',
            label: questionData.label || '',
            
            // 数字字段，确保正确类型转换
            courseLevelId: String(questionData.courseLevelId || ''),
            questionType: String(questionData.questionType || ''),
            difficulty: String(questionData.difficulty || ''),
            isPublic: questionData.isPublic !== undefined ? Number(questionData.isPublic) : 1,
            strict: '1', // 🔥 固定为严格判题模式，始终传 "1"
            timeLimit: Number(questionData.timeLimit || 1000),
            spaceLimitation: Number(questionData.spaceLimitation || 268435456),
            
            // 新增字段映射
            inputFormat: questionData.inputFormat || '',
            outputFormat: questionData.outputFormat || '',
            outputType: '', // 将在下面根据 outputFormat 内容自动设置
            rangeAndPrompt: questionData.rangeAndPrompt || '',
            testCases: questionData.testCases || '',  // 测试用例
            testCode: questionData.testCode || '',    // 答案代码
            testData: questionData.testData || '',    // 测试数据
            // 修复：如果后端返回的createUserId有精度问题，使用JWT中的正确ID
            createUserId: this.getCorrectUserId(questionData.createUserId),
            submissionQuantity: questionData.submissionQuantity || 0,
            byQuantity: questionData.byQuantity || 0
          };
          
          // 🔥 根据 outputFormat 内容自动设置 outputType（UI控制用）
          if (questionData.outputFormat) {
            // 如果 outputFormat 是图片URL，设置为 local
            if (this.isImageUrl(questionData.outputFormat)) {
              this.formData.outputType = 'local';
              logger.log('📊 [QuestionEdit] 输出格式类型: local (检测到图片URL)');
            } else {
              // 否则是文本描述
              this.formData.outputType = 'text';
              logger.log('📊 [QuestionEdit] 输出格式类型: text (文本描述)');
            }
          } else {
            // 没有输出格式，不设置（让用户选择）
            this.formData.outputType = '';
            logger.log('📊 [QuestionEdit] 输出格式类型: 未设置（用户需选择）');
          }
          
          // 根据后端返回的pictureType设置uploadType
          if (questionData.pictureType === 'local') {
            this.uploadType = 'file'; // local表示上传本地图片
            logger.log('📊 [QuestionEdit] 题目图片类型: file (从pictureType=local)');
          } else {
            this.uploadType = 'url'; // 其他情况使用远程URL
            logger.log('📊 [QuestionEdit] 题目图片类型: url (从pictureType=' + questionData.pictureType + ')');
          }
          
          logger.log('📊 [QuestionEdit] 最终设置 - 输出格式类型:', this.outputFormatType, ', 题目图片类型:', this.uploadType);
          
          // 🔥 解析测试用例字符串到数组
          if (questionData.testCases && typeof questionData.testCases === 'string') {
            try {
              const parsedTestCases = JSON.parse(questionData.testCases);
              logger.log('✅ [QuestionEdit] 测试用例解析成功:', parsedTestCases);
              
              if (Array.isArray(parsedTestCases)) {
                this.testCases = parsedTestCases.map(tc => {
                  const isImage = this.isImageUrl(tc.output);
                  logger.log('🔍 [QuestionEdit] 解析测试用例:');
                  logger.log('  - input:', tc.input);
                  logger.log('  - output:', tc.output);
                  logger.log('  - 是否图片:', isImage);
                  
                  return {
                    inputFormat: tc.input || '',
                    outputType: isImage ? 'image' : 'text',
                    outputFormat: isImage ? '' : (tc.output || ''),
                    outputFile: null,
                    outputFilePath: isImage ? tc.output : null,
                    uploading: false
                  };
                });
                logger.log('✅ [QuestionEdit] 测试用例数组已填充:', this.testCases);
              }
            } catch (error) {
              logger.error('❌ [QuestionEdit] 测试用例解析失败:', error);
              this.testCases = [];
            }
          }
          
          // 🔥 解析测试数据字符串到数组
          if (questionData.testData && typeof questionData.testData === 'string') {
            try {
              const parsedTestData = JSON.parse(questionData.testData);
              logger.log('✅ [QuestionEdit] 测试数据解析成功:', parsedTestData);
              
              if (Array.isArray(parsedTestData)) {
                this.testDataItems = parsedTestData.map(td => ({
                  content: td.content || ''
                }));
                logger.log('✅ [QuestionEdit] 测试数据数组已填充:', this.testDataItems);
              }
            } catch (error) {
              logger.error('❌ [QuestionEdit] 测试数据解析失败:', error);
              this.testDataItems = [];
            }
          }
          
          logger.log('✅ [QuestionEdit] 表单数据已填充:', this.formData);
          logger.log('📝 [QuestionEdit] 表单字段检查:');
          logger.log('  - 🆔 题目ID (后端返回):', this.formData.id);
          logger.log('  - 🆔 路由参数ID:', this.questionId);
          logger.log('  - 📝 题目名称:', this.formData.questionName);
          logger.log('  - 👤 创建用户ID (字符串):', this.formData.createUserId);
          logger.log('  - 👤 创建用户ID类型:', typeof this.formData.createUserId);
          logger.log('  - 📄 题目描述:', this.formData.questionDescription ? '有内容' : '空');
          logger.log('  - 🎓 课程等级:', this.formData.courseLevelId);
          logger.log('  - 📊 题目类型:', this.formData.questionType);
          logger.log('  - ⭐ 难度等级:', this.formData.difficulty);
          
          // 重要：验证后端返回的ID与路由参数ID的关系
          if (this.formData.id && String(this.formData.id) !== String(this.questionId)) {
            logger.warn('⚠️ [QuestionEdit] ID不匹配！');
            logger.warn('  - 后端返回ID:', this.formData.id, typeof this.formData.id);
            logger.warn('  - 路由参数ID:', this.questionId, typeof this.questionId);
            logger.warn('  - 这是正常的，将使用后端返回的ID进行保存');
          }
          
          // 同步后端数据到本地存储，确保本地存储使用正确的ID
          try {
            const { default: localQuestionStorage } = await import('@/utils/localStorage');
            localQuestionStorage.syncQuestionFromBackend(questionData);
            logger.log('🔄 [QuestionEdit] 后端数据已同步到本地存储');
          } catch (syncError) {
            logger.warn('⚠️ [QuestionEdit] 同步数据到本地存储失败:', syncError);
          }
        } else {
          throw new Error('题目不存在');
        }
        
      } catch (error) {
        logger.error('❌ [QuestionEdit] 加载题目数据失败:', error);
        if (this.$message && this.$message.error) {
          this.$message.error('加载题目数据失败，请重试');
        } else {
          alert('加载题目数据失败，请重试');
        }
        this.goBack();
      } finally {
        this.isLoading = false;
      }
    },

    async updateQuestion() {
      logger.log('🎬 [QuestionEdit] ========== 开始更新题目 ==========');
      
      if (!this.validateForm()) {
        logger.log('❌ [QuestionEdit] 表单验证失败，停止提交');
        return;
      }

      logger.log('⏳ [QuestionEdit] 设置提交状态...');
      this.isSubmitting = true;
      
      // 验证测试用例
      for (let i = 0; i < this.testCases.length; i++) {
        const tc = this.testCases[i];
        if (tc.outputType === 'image' && !tc.outputFilePath) {
          const errorMsg = `测试用例${i + 1}选择了图片输出但图片未上传成功，请重新上传`;
          logger.error('❌ [QuestionEdit]', errorMsg);
          if (this.$message && this.$message.error) {
            this.$message.error(errorMsg);
          } else {
            alert('❌ ' + errorMsg);
          }
          return;
        }
      }
      
      try {
        logger.log('🚀 [QuestionEdit] 开始更新题目...');
        logger.log('📝 [QuestionEdit] 题目数据:', this.formData);
        logger.log('🆔 [QuestionEdit] 题目ID:', this.questionId);

        // 使用后端传回的原始题目ID，不进行任何转换
        logger.log('🆔 [QuestionEdit] 使用原始题目ID:', this.formData.id);
        logger.log('🆔 [QuestionEdit] 路由参数ID:', this.questionId);
        
        // 验证必须有题目ID
        if (!this.formData.id) {
          logger.error('❌ [QuestionEdit] 缺少题目ID，无法提交');
          throw new Error('缺少题目ID，请重新加载页面');
        }

        // 确保数据类型正确，使用后端传回的原始ID
        const submitData = {
          ...this.formData,
          // 确保ID字段存在且使用正确的值
          courseLevelId: Number(this.formData.courseLevelId),
          questionType: Number(this.formData.questionType),
          isPublic: Number(this.formData.isPublic),
          strict: '1', // 🔥 固定为严格判题模式，始终传 "1"（string类型）
          timeLimit: Number(this.formData.timeLimit),
          spaceLimitation: Number(this.formData.spaceLimitation),
          testCases: JSON.stringify(this.testCases.map(tc => ({
            input: tc.inputFormat || '',  // 输入格式放进input
            output: tc.outputType === 'image' ? (tc.outputFilePath || '') : (tc.outputFormat || '')  // 输出格式（文本或图片路径）放进output
          }))), // 将测试用例数组转换为指定格式的JSON字符串
          testData: JSON.stringify(this.testDataItems.map(td => ({
            content: td.content || ''  // 测试数据内容
          }))), // 将测试数据数组转换为指定格式的JSON字符串
          testCode: String(this.formData.testCode || ''),   // 答案代码
          difficulty: Number(this.formData.difficulty),
          submissionQuantity: Number(this.formData.submissionQuantity || 0),
          byQuantity: Number(this.formData.byQuantity || 0),
          // 修复：使用正确的用户ID，避免精度丢失
          createUserId: this.getCorrectUserId(this.formData.createUserId)
        };
        
        logger.log('📋 [QuestionEdit] 测试用例数据:', submitData.testCases);
        logger.log('📋 [QuestionEdit] 答案数据:', submitData.testCode);
        
        logger.log('🔄 [QuestionEdit] 提交数据:', submitData);
        logger.log('🆔 [QuestionEdit] 确认提交的题目ID:', submitData.id);
        logger.log('📝 [QuestionEdit] 提交数据完整性检查:');
        logger.log('  - ID:', submitData.id);
        logger.log('  - 题目名称:', submitData.questionName);
        logger.log('  - 题目描述长度:', submitData.questionDescription?.length || 0);
        logger.log('  - 👤 创建用户ID (修复后):', submitData.createUserId);
        logger.log('  - 👤 创建用户ID类型:', typeof submitData.createUserId);
        logger.log('  - 👤 创建用户ID长度:', submitData.createUserId?.length, '位');

        // 🔥 简化：后端不需要 outputType，outputFormat 可以是文本或图片路径
        // outputFormat 的值：
        //   - 文本描述时：用户填写的文本内容
        //   - 上传图片时：后端返回的图片路径
        // 后端会自动判断 outputFormat 是文本还是图片路径
        
        // 删除 outputType 和 outputFile 字段（后端不需要）
        delete submitData.outputType;
        delete submitData.outputFile;
        
        logger.log('✅ [QuestionEdit] 输出格式处理完成:');
        logger.log('  - inputFormat:', submitData.inputFormat);
        logger.log('  - outputFormat:', submitData.outputFormat, '(可能是文本或图片路径)');

        // 优先使用管理员API接口，失败时使用本地存储作为备用
        let updateResult = null;
        
        try {
          logger.log('🌐 [QuestionEdit] 尝试使用新的测试题目API更新题目...');
          logger.log('🖼️ [QuestionEdit] 上传类型:', this.uploadType);
          
          if (this.uploadType === 'file' && this.selectedFile) {
            // 直接传递文件对象，不转换为base64
            logger.log('📤 [QuestionEdit] 使用文件对象上传');
            logger.log('📸 [QuestionEdit] 文件信息:', {
              name: this.selectedFile.name,
              type: this.selectedFile.type,
              size: this.selectedFile.size
            });
            
            // 直接传递File对象到submitData
            submitData.pictureFile = this.selectedFile; // 传递File对象
            submitData.pictureType = 'local'; // 设置为local表示本地文件
            
            logger.log('📝 [QuestionEdit] 提交数据包含文件对象');
            
            // 调用form-data格式的接口更新题目
            updateResult = await updateTestQuestion(submitData);
          } else {
            // 远程图片URL - 使用form-data请求
            updateResult = await updateTestQuestion(submitData);
          }
          
          logger.log('🎉 [QuestionEdit] API更新结果:', updateResult);
          
          // 检查API响应是否真正成功
          if (updateResult && updateResult.data) {
            // 检查响应数据中的状态
            if (updateResult.data.code === 0) {
              logger.log('✅ [QuestionEdit] API更新成功（code = 0）');
              
              // API成功后，同步更新本地存储
              try {
                const { default: localQuestionStorage } = await import('@/utils/localStorage');
                localQuestionStorage.updateQuestion(submitData.id, submitData);
                logger.log('💾 [QuestionEdit] 已同步更新本地存储');
              } catch (syncError) {
                logger.warn('⚠️ [QuestionEdit] 同步本地存储失败:', syncError);
              }
              
              // 记录成功日志
              logger.log('✅ [QuestionEdit] 题目更新成功');
              
              // 🔥 跳转回我的试题页面
              logger.log('🚀 [QuestionEdit] 准备跳转到我的试题页面...');
              setTimeout(() => {
                logger.log('🚀 [QuestionEdit] 执行跳转');
                this.$router.push('/my-questions');
              }, 1500);
              
              return; // 成功后直接返回，不执行后续代码
              
            } else {
              // 🔥 code !== 0，表示更新失败
              logger.error('❌ [QuestionEdit] 更新失败，业务状态码异常');
              logger.error('❌ [QuestionEdit] code:', updateResult.data.code);
              logger.error('❌ [QuestionEdit] message:', updateResult.data.message);
              
              const errorMsg = updateResult.data.message || '更新题目失败，请检查输入信息';
              if (this.$message && this.$message.error) {
                this.$message.error(errorMsg);
              } else {
                alert('❌ ' + errorMsg);
              }
              
              return; // 失败后直接返回，不执行后续代码
            }
          } else {
            logger.warn('⚠️ [QuestionEdit] API响应异常，尝试本地存储备用方案');
            logger.warn('⚠️ [QuestionEdit] 响应内容:', updateResult);
            throw new Error('API更新响应异常');
          }
        } catch (apiError) {
          logger.warn('⚠️ [QuestionEdit] API更新失败，使用本地存储备用方案:', apiError);
          
          // 备用方案：调用本地存储更新题目
          const { default: localQuestionStorage } = await import('@/utils/localStorage');
          // 使用表单数据中的ID而不是路由参数ID
          updateResult = localQuestionStorage.updateQuestion(submitData.id, submitData);
          logger.log('💾 [QuestionEdit] 本地存储使用的ID:', submitData.id);
          logger.log('🎉 [QuestionEdit] 本地存储更新结果:', updateResult);
          
          // 🔥 本地存储成功后才显示成功消息
          logger.log('✅ [QuestionEdit] 题目已保存到本地存储');
          
          // 跳转回我的试题页面
          setTimeout(() => {
            this.$router.push('/my-questions');
          }, 1500);
        }
        
      } catch (error) {
        logger.error('❌ [QuestionEdit] 更新题目失败:', error);
        logger.error('❌ [QuestionEdit] 错误详情:', error.message);
        
        // 🔥 根据后端返回的实际错误信息显示
        let errorMsg = '更新题目失败，请重试';
        
        // 尝试从各种可能的位置获取后端错误信息
        if (error.response?.data?.message) {
          errorMsg = error.response.data.message;
        } else if (error.data?.message) {
          errorMsg = error.data.message;
        } else if (error.message) {
          errorMsg = error.message;
        }
        
        logger.error('❌ [QuestionEdit] 显示错误消息:', errorMsg);
        
        if (this.$message && this.$message.error) {
          this.$message.error(errorMsg);
        } else {
          alert('❌ ' + errorMsg);
        }
      } finally {
        logger.log('🔄 [QuestionEdit] 重置提交状态...');
        this.isSubmitting = false;
        logger.log('🎬 [QuestionEdit] ========== 更新流程结束 ==========');
      }
    },

    validateForm() {
      const required = ['questionName', 'courseLevelId', 'questionType', 'difficulty', 'questionDescribe', 'rangeAndPrompt'];
      
      logger.log('🔍 [QuestionEdit] 开始表单验证...');
      
      for (let field of required) {
        if (!this.formData[field]) {
          logger.error(`❌ [QuestionEdit] 缺少必填字段: ${field}`);
          const errorMsg = `请填写${this.getFieldLabel(field)}`;
          if (this.$message && this.$message.error) {
            this.$message.error(errorMsg);
          } else {
            alert(errorMsg);
          }
          return false;
        }
      }
      
      logger.log('✅ [QuestionEdit] 表单验证通过');

      if (this.formData.timeLimit < 100 || this.formData.timeLimit > 10000) {
        const errorMsg = '时间限制应在100-10000毫秒之间';
        if (this.$message && this.$message.error) {
          this.$message.error(errorMsg);
        } else {
          alert(errorMsg);
        }
        return false;
      }

      if (this.formData.spaceLimitation < 1048576) {
        const errorMsg = '空间限制不能小于1MB';
        if (this.$message && this.$message.error) {
          this.$message.error(errorMsg);
        } else {
          alert(errorMsg);
        }
        return false;
      }

      return true;
    },

    getFieldLabel(field) {
      const labels = {
        questionName: '题目名称',
        courseLevelId: '课程等级',
        questionType: '题目类型',
        difficulty: '难度等级',
        questionDescribe: '题目描述',
        inputFormat: '输入格式',
        outputFormat: '输出格式',
        rangeAndPrompt: '数据范围和提示'
      };
      return labels[field] || field;
    },

    // 添加测试用例
    addTestCase() {
      this.testCases.push({
        inputFormat: '',
        outputType: 'text',  // 默认为文本描述
        outputFormat: '',
        outputFile: null,  // 输出格式图片文件
        outputFilePath: null,  // 输出格式图片路径（后端返回）
        uploading: false  // 上传中状态
      })
      logger.log('➕ [QuestionEdit] 添加测试用例，当前数量:', this.testCases.length)
    },
    
    // 删除测试用例
    removeTestCase(index) {
      if (confirm('确定要删除这个测试用例吗？')) {
        this.testCases.splice(index, 1)
        logger.log('🗑️ [QuestionEdit] 删除测试用例，当前数量:', this.testCases.length)
      }
    },
    
    // 添加测试数据
    addTestData() {
      this.testDataItems.push({
        content: ''
      })
      logger.log('➕ [QuestionEdit] 添加测试数据，当前数量:', this.testDataItems.length)
    },
    
    // 删除测试数据
    removeTestData(index) {
      if (confirm('确定要删除这条测试数据吗？')) {
        this.testDataItems.splice(index, 1)
        logger.log('🗑️ [QuestionEdit] 删除测试数据，当前数量:', this.testDataItems.length)
      }
    },
    
    // 触发测试用例输出格式文件选择
    triggerTestCaseOutputFileInput(index) {
      const inputElement = this.$refs['testCaseOutputFileInput' + index]
      if (inputElement && inputElement[0]) {
        inputElement[0].click()
      }
    },
    
    // 处理测试用例输出格式文件选择
    async handleTestCaseOutputFileSelect(event, index) {
      const file = event.target.files[0]
      if (file) {
        // 验证文件大小（5MB限制）
        if (file.size > 5 * 1024 * 1024) {
          alert('图片文件不能超过5MB')
          return
        }
        
        // 设置上传中状态
        if (this.testCases && Array.isArray(this.testCases) && this.testCases[index]) {
          this.testCases[index].uploading = true
        }
        
        // 自动上传文件
        try {
          logger.log(`📤 [QuestionEdit] 开始上传测试用例${index + 1}输出格式图片...`)
          
          const response = await uploadFile(file)
          
          if (response && response.code === 0 && response.data) {
            // 保存文件对象和后端返回的图片路径
            if (this.testCases && Array.isArray(this.testCases) && this.testCases[index]) {
              this.testCases[index].outputFile = file
              this.testCases[index].outputFilePath = response.data  // 保存图片路径
            }
            
            logger.log(`✅ [QuestionEdit] 测试用例${index + 1}图片上传成功，路径:`, response.data)
          } else {
            throw new Error(response?.message || '上传失败')
          }
        } catch (error) {
          logger.error(`❌ [QuestionEdit] 测试用例${index + 1}图片上传失败:`, error)
          
          const errorMsg = error.response?.data?.message || error.message || '图片上传失败'
          if (this.$message && this.$message.error) {
            this.$message.error(errorMsg)
          } else {
            alert('❌ ' + errorMsg)
          }
        } finally {
          // 清除上传中状态
          if (this.testCases && Array.isArray(this.testCases) && this.testCases[index]) {
            this.testCases[index].uploading = false
          }
        }
      }
    },
    
    // 清除测试用例输出格式文件（用于更换图片）
    clearTestCaseOutputFile(index) {
      // 清除文件对象和路径，允许重新选择
      if (this.testCases && Array.isArray(this.testCases) && this.testCases[index]) {
        this.testCases[index].outputFile = null
        this.testCases[index].outputFilePath = null
        this.testCases[index].uploading = false
      }
      logger.log(`🗑️ [QuestionEdit] 清除测试用例${index + 1}输出格式图片，允许重新上传`)
    },
    
    // 🔥 触发全局输出格式图片选择
    triggerOutputImageInput() {
      const inputElement = this.$refs.outputImageInput
      if (inputElement) {
        inputElement.click()
      }
    },
    
    // 🔥 处理全局输出格式图片上传
    async handleOutputImageUpload(event) {
      const file = event.target.files[0]
      if (!file) return
      
      // 验证文件大小（5MB限制）
      if (file.size > 5 * 1024 * 1024) {
        alert('图片文件不能超过5MB')
        return
      }
      
      // 设置上传中状态
      this.uploadingOutputImage = true
      
      try {
        logger.log('📤 [QuestionEdit] 开始上传输出格式图片...')
        
        const response = await uploadFile(file)
        
        if (response && response.code === 0 && response.data) {
          // 🔥 将后端返回的图片路径保存到 outputFormat 字段
          this.formData.outputFormat = response.data
          logger.log('✅ [QuestionEdit] 输出格式图片上传成功，路径已保存到 outputFormat:', response.data)
          
          if (this.$message && this.$message.success) {
            this.$message.success({
              message: '图片上传成功',
              duration: 1000
            })
          }
        } else {
          throw new Error(response?.message || '上传失败')
        }
      } catch (error) {
        logger.error('❌ [QuestionEdit] 输出格式图片上传失败:', error)
        
        const errorMsg = error.response?.data?.message || error.message || '图片上传失败'
        if (this.$message && this.$message.error) {
          this.$message.error(errorMsg)
        } else {
          alert('❌ ' + errorMsg)
        }
        
        // 清除文件选择
        event.target.value = ''
      } finally {
        // 清除上传中状态
        this.uploadingOutputImage = false
      }
    },
    
    // 🔥 移除全局输出格式图片
    removeOutputImage() {
      this.formData.outputFormat = ''
      logger.log('🗑️ [QuestionEdit] 移除输出格式图片，清空 outputFormat')
    },
    
    // 🔥 触发题目描述图片选择
    triggerDescribeImageInput() {
      const inputElement = this.$refs.describeImageInput
      if (inputElement) {
        inputElement.click()
      }
    },
    
    // 🔥 处理题目描述图片上传
    async handleDescribeImageUpload(event) {
      const file = event.target.files[0]
      if (!file) return
      
      // 验证文件大小（5MB限制）
      if (file.size > 5 * 1024 * 1024) {
        alert('图片文件不能超过5MB')
        return
      }
      
      // 设置上传中状态
      this.uploadingDescribeImage = true
      
      try {
        logger.log('📤 [QuestionEdit] 开始上传题目描述图片...')
        
        const response = await uploadFile(file)
        
        if (response && response.code === 0 && response.data) {
          // 保存后端返回的图片路径到 questionDescribePicture 字段
          this.formData.questionDescribePicture = response.data
          logger.log('✅ [QuestionEdit] 题目描述图片上传成功，路径:', response.data)
          
          if (this.$message && this.$message.success) {
            this.$message.success({
              message: '图片上传成功',
              duration: 1000
            })
          }
        } else {
          throw new Error(response?.message || '上传失败')
        }
      } catch (error) {
        logger.error('❌ [QuestionEdit] 题目描述图片上传失败:', error)
        
        const errorMsg = error.response?.data?.message || error.message || '图片上传失败'
        if (this.$message && this.$message.error) {
          this.$message.error(errorMsg)
        } else {
          alert('❌ ' + errorMsg)
        }
        
        // 清除文件选择
        event.target.value = ''
      } finally {
        // 清除上传中状态
        this.uploadingDescribeImage = false
      }
    },
    
    // 🔥 移除题目描述图片
    removeDescribeImage() {
      this.formData.questionDescribePicture = ''
      logger.log('🗑️ [QuestionEdit] 移除题目描述图片')
    },

    // 判断是否是图片URL
    isImageUrl(text) {
      if (!text) return false
      
      // 包含图片文件扩展名
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
      const lowerText = text.toLowerCase()
      
      // 检查是否包含图片扩展名
      const hasImageExtension = imageExtensions.some(ext => lowerText.includes(ext))
      
      // 检查是否是URL格式（http开头或包含特殊格式）
      const isUrl = text.startsWith('http') || 
                    text.startsWith('/api/') || 
                    text.includes('文件上传成功')
      
      return hasImageExtension && isUrl
    },
    
    // 获取图片URL
    getImageUrl(imagePath) {
      if (!imagePath) return ''
      
      // 🔥 处理后端返回的特殊格式："文件上传成功，文件的url为：[URL]"
      if (imagePath.includes('文件上传成功') && imagePath.includes('url为：')) {
        const urlMatch = imagePath.match(/url为：(.+)$/);
        if (urlMatch && urlMatch[1]) {
          const extractedUrl = urlMatch[1].trim();
          logger.log('✅ [QuestionEdit] 从特殊格式中提取URL:', extractedUrl);
          return extractedUrl;
        }
      }
      
      // 如果已经是完整URL，直接返回
      if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
        return imagePath
      }
      
      // 拼接完整URL（相对路径）
      const GLOBAL_CONFIG = window.GLOBAL_CONFIG || {}
      const baseURL = GLOBAL_CONFIG.API_BASE_URL || 'http://localhost:8000'
      const fullUrl = baseURL + imagePath
      
      return fullUrl
    },

    goBack() {
      this.$router.push('/my-questions');
    },

    async deleteQuestion() {
      // 确认删除
      const confirmDelete = confirm('⚠️ 确定要删除这个题目吗？\n\n题目名称：' + this.formData.questionName + '\n\n此操作不可撤销！');
      
      if (!confirmDelete) {
        logger.log('🚫 [QuestionEdit] 用户取消删除操作');
        return;
      }

      logger.log('🗑️ [QuestionEdit] 开始删除题目...');
      logger.log('🆔 [QuestionEdit] 删除题目ID:', this.formData.id);
      logger.log('📝 [QuestionEdit] 删除题目名称:', this.formData.questionName);

      this.isDeleting = true;

      try {
        // 验证必须有题目ID
        if (!this.formData.id) {
          throw new Error('缺少题目ID，无法删除');
        }

        // 优先尝试API删除，失败时使用本地存储
        let deleteResult = null;
        
        try {
          logger.log('🌐 [QuestionEdit] 尝试使用API删除题目...');
          logger.log('🆔 [QuestionEdit] 传递给后端的题目ID:', this.formData.id);
          
          // 调用新的测试题目删除接口
          const response = await deleteTestQuestion(this.formData.id);
          
          logger.log('✅ [QuestionEdit] API删除响应:', response);
          
          // 检查删除结果
          if (response && response.data) {
            // 检查响应数据中的状态
            if (response.data.code === 0) {
              logger.log('✅ [QuestionEdit] API删除成功');
              deleteResult = response;
            } else {
              throw new Error(`API删除失败: ${response.data.message || '未知错误'}`);
            }
          } else {
            throw new Error('API删除响应异常');
          }
        } catch (apiError) {
          logger.warn('⚠️ [QuestionEdit] API删除失败，使用本地存储:', apiError);
          
          // 备用方案：从本地存储删除题目
          const { default: localQuestionStorage } = await import('@/utils/localStorage');
          deleteResult = localQuestionStorage.deleteQuestion(this.formData.id);
          logger.log('🗑️ [QuestionEdit] 本地存储删除结果:', deleteResult);
        }

        logger.log('✅ [QuestionEdit] 题目删除成功');

        // 延迟跳转，让用户看到成功消息
        setTimeout(() => {
          // 通过查询参数告知需要刷新数据
          this.$router.push({
            path: '/my-questions',
            query: { refresh: Date.now() }
          });
        }, 1000);

      } catch (error) {
        logger.error('❌ [QuestionEdit] 删除题目失败:', error);
        
        // 显示错误消息
        if (this.$message && this.$message.error) {
          this.$message.error('删除题目失败：' + error.message);
        } else {
          alert('删除题目失败：' + error.message);
        }
      } finally {
        this.isDeleting = false;
      }
    },

    // 获取当前用户ID（保持字符串格式，避免精度丢失）
    getCurrentUserId() {
      try {
        // 首先尝试从JWT令牌中解析用户ID（修复精度丢失问题）
        const token = localStorage.getItem('token');
        if (token) {
          try {
            const tokenParts = token.split('.');
            if (tokenParts.length === 3) {
              // 关键修复：直接解析base64字符串，避免JSON.parse的数字精度丢失
              const payloadBase64 = tokenParts[1];
              const payloadStr = atob(payloadBase64);
              logger.log('🔍 [QuestionEdit] JWT payload字符串:', payloadStr);
              
              // 使用正则表达式提取ID，保持字符串格式
              const idMatch = payloadStr.match(/"id":(\d+)/);
              if (idMatch && idMatch[1]) {
                const userId = idMatch[1]; // 保持字符串格式
                logger.log('👤 [QuestionEdit] 从JWT令牌获取用户ID (字符串格式):', userId);
                logger.log('👤 [QuestionEdit] 用户ID长度:', userId.length, '位');
                logger.log('🔍 [QuestionEdit] JWT payload原始内容:', payloadStr);
                logger.log('🔍 [QuestionEdit] 正则匹配结果:', idMatch);
                return userId;
              }
            }
          } catch (parseError) {
            logger.error('❌ [QuestionEdit] JWT解析失败:', parseError);
          }
        }
        
        // 备用方案：从userInfo获取
        const userInfoStr = localStorage.getItem('userInfo');
        if (userInfoStr) {
          try {
            const userInfo = JSON.parse(userInfoStr);
            if (userInfo && userInfo.id) {
              const userId = String(userInfo.id);
              logger.log('👤 [QuestionEdit] 从userInfo获取用户ID:', userId);
              return userId;
            }
          } catch (parseError) {
            logger.error('❌ [QuestionEdit] userInfo解析失败:', parseError);
          }
        }
        
        logger.error('❌ [QuestionEdit] 无法获取用户ID');
        return null;
      } catch (error) {
                 logger.error('❌ [QuestionEdit] getCurrentUserId出错:', error);
         return null;
       }
     },

     // 获取正确的用户ID，修复精度丢失问题
     getCorrectUserId(backendUserId) {
       try {
         // 从JWT获取正确的用户ID
         const jwtUserId = this.getCurrentUserId();
         logger.log('🔍 [QuestionEdit] 用户ID比较:');
         logger.log('  - 后端返回的ID:', backendUserId);
         logger.log('  - JWT中的正确ID:', jwtUserId);
         
         // 如果后端ID和JWT ID不一致，优先使用JWT中的正确ID
         if (backendUserId && jwtUserId && String(backendUserId) !== String(jwtUserId)) {
           logger.log('⚠️ [QuestionEdit] 检测到用户ID精度丢失，使用JWT中的正确ID');
           logger.log('  - 错误的ID:', backendUserId);
           logger.log('  - 正确的ID:', jwtUserId);
           return jwtUserId;
         }
         
         // 如果一致或者没有JWT ID，使用后端ID
         return String(backendUserId || jwtUserId || '');
       } catch (error) {
         logger.error('❌ [QuestionEdit] getCorrectUserId出错:', error);
         return String(backendUserId || '');
             }
    },

    // 图片上传相关方法
    triggerFileInput() {
      this.$refs.fileInput.click()
    },

    handleFileSelect(event) {
      const file = event.target.files[0]
      if (file) {
        this.validateAndSetFile(file)
      }
    },

    handleFileDrop(event) {
      const files = event.dataTransfer.files
      if (files.length > 0) {
        this.validateAndSetFile(files[0])
      }
    },

    validateAndSetFile(file) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件（JPG、PNG、GIF等格式）')
        return
      }

      // 检查文件大小（5MB限制）
      const maxSize = 5 * 1024 * 1024 // 5MB
      if (file.size > maxSize) {
        alert('图片大小不能超过5MB')
        return
      }

      this.selectedFile = file
      logger.log('✅ [QuestionEdit] 文件选择成功:', file.name, '大小:', (file.size / 1024 / 1024).toFixed(2) + 'MB')
    },

    clearFile() {
      this.selectedFile = null
      this.$refs.fileInput.value = ''
    },

    // 输出格式图片上传相关方法
    triggerOutputFileInput() {
      this.$refs.outputFileInput.click()
    },

    handleOutputFileSelect(event) {
      const file = event.target.files[0]
      if (file) {
        this.validateAndSetOutputFile(file)
      }
    },

    handleOutputFileDrop(event) {
      const files = event.dataTransfer.files
      if (files.length > 0) {
        this.validateAndSetOutputFile(files[0])
      }
    },

    validateAndSetOutputFile(file) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件（JPG、PNG、GIF等格式）')
        return
      }

      // 检查文件大小（5MB限制）
      const maxSize = 5 * 1024 * 1024 // 5MB
      if (file.size > maxSize) {
        alert('图片大小不能超过5MB')
        return
      }

      this.selectedOutputFile = file
      logger.log('✅ [QuestionEdit] 输出格式图片选择成功:', file.name, '大小:', (file.size / 1024 / 1024).toFixed(2) + 'MB')
    },

    removeOutputFile() {
      this.selectedOutputFile = null
      if (this.$refs.outputFileInput) {
        this.$refs.outputFileInput.value = ''
      }
    },

    getOutputImagePreviewURL() {
      if (this.selectedOutputFile) {
        return URL.createObjectURL(this.selectedOutputFile)
      }
      return ''
    },

    onImageError(event) {
      logger.error('❌ [QuestionEdit] 图片预览加载失败:', event.target.src)
      event.target.style.display = 'none'
    },

    // 将文件转换为base64字符串
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = () => {
          // 移除data:image/xxx;base64,前缀，只保留base64字符串
          const base64 = reader.result.split(',')[1]
          resolve(base64)
        }
        reader.onerror = () => {
          reject(new Error('文件读取失败'))
        }
        reader.readAsDataURL(file)
      })
    }
  },

  async mounted() {
    logger.log('📋 [QuestionEdit] 题目编辑页面已加载');
    
    // 获取题目ID
    this.questionId = this.$route.params.id;
    logger.log('🆔 [QuestionEdit] 题目ID:', this.questionId);
    
    if (!this.questionId) {
      logger.error('❌ [QuestionEdit] 没有提供题目ID');
      if (this.$message && this.$message.error) {
        this.$message.error('题目ID缺失');
      } else {
        alert('题目ID缺失');
      }
      this.goBack();
      return;
    }
    
    // 加载题目数据
    await this.loadQuestionData();
  }
}
</script>

<style scoped>
/* 复用 QuestionCreate.vue 的样式 */
.question-edit-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.header-content {
  background: rgba(255, 255, 255, 0.95);
  padding: 30px;
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  display: inline-block;
}

.page-title {
  font-size: 2.5em;
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-weight: 700;
}

.page-title i {
  color: #667eea;
  margin-right: 15px;
}

.page-subtitle {
  font-size: 1.1em;
  color: #7f8c8d;
  margin: 0;
}

.content-wrapper {
  max-width: 1000px;
  margin: 0 auto;
}

.question-form {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.form-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.form-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-header {
  background: linear-gradient(135deg, #667eea, #764ba2);
  padding: 20px 30px;
  color: white;
}

.card-header h3 {
  margin: 0;
  font-size: 1.3em;
  font-weight: 600;
}

.card-header i {
  margin-right: 10px;
}

.card-content {
  padding: 30px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.form-row:last-child {
  margin-bottom: 0;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
  font-size: 0.95em;
}

.required {
  color: #e74c3c;
  font-weight: bold;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 12px 15px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 0.95em;
  transition: all 0.3s ease;
  background: white;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  transform: translateY(-2px);
}

.form-group textarea {
  resize: vertical;
  min-height: 60px;
  font-family: inherit;
}

.form-hint {
  margin-top: 5px;
  font-size: 0.85em;
  color: #7f8c8d;
  font-style: italic;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 30px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.btn {
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  font-size: 1em;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.btn-secondary {
  background: #95a5a6;
  color: white;
}

.btn-secondary:hover {
  background: #7f8c8d;
  transform: translateY(-2px);
}

.btn-danger {
  background: #e74c3c;
  color: white;
  border: 2px solid #e74c3c;
}

.btn-danger:hover:not(:disabled) {
  background: #c0392b;
  border-color: #c0392b;
  transform: translateY(-2px);
}

.btn-danger:disabled {
  background: #bdc3c7;
  border-color: #bdc3c7;
  cursor: not-allowed;
  transform: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .question-edit-container {
    padding: 10px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .page-title {
    font-size: 2em;
  }
  
  .card-content {
    padding: 20px;
  }
  
  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .btn {
    justify-content: center;
  }
}

/* 图片上传样式 */
.image-upload-options {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.upload-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.upload-option input[type="radio"] {
  margin: 0;
  width: auto;
}

.upload-option label {
  margin: 0;
  cursor: pointer;
  font-weight: normal;
}

.upload-section {
  margin-top: 15px;
}

.upload-section input[type="url"] {
  width: 100%;
  min-width: 400px;
  padding: 12px 15px;
  font-size: 14px;
  border: 2px solid #ddd;
  border-radius: 8px;
  transition: border-color 0.3s ease;
}

.upload-section input[type="url"]:focus {
  border-color: #3498db;
  outline: none;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.file-upload-area {
  border: 2px dashed #ddd;
  border-radius: 10px;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
  position: relative;
}

.file-upload-area:hover {
  border-color: #3498db;
  background: rgba(52, 152, 219, 0.05);
}

.upload-placeholder i {
  font-size: 48px;
  color: #bdc3c7;
  margin-bottom: 15px;
  display: block;
}

.upload-placeholder p {
  font-size: 16px;
  color: #7f8c8d;
  margin-bottom: 10px;
}

.upload-placeholder small {
  color: #95a5a6;
  font-size: 14px;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 15px;
  background: rgba(52, 152, 219, 0.1);
  border-radius: 8px;
  margin: 10px 0;
}

.file-info i {
  color: #3498db;
  font-size: 20px;
}

.file-info span {
  font-weight: 500;
  color: #2c3e50;
}

.clear-btn {
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s;
}

.clear-btn:hover {
  background: #c0392b;
}

.uploaded-image {
  position: relative;
  display: inline-block;
}

.preview-image {
  max-width: 300px;
  max-height: 200px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.uploaded-image .clear-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #e74c3c;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.upload-actions {
  margin-top: 15px;
  text-align: center;
}

.upload-btn {
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.upload-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #2980b9, #21618c);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}

.upload-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.image-preview {
  margin-top: 15px;
  text-align: center;
}

.image-preview .preview-image {
  max-width: 300px;
  max-height: 200px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.current-image {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  text-align: center;
}

.current-image .image-label {
  font-size: 14px;
  color: #495057;
  margin-bottom: 10px;
}

.current-image .preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.current-image .form-hint {
  display: block;
  margin-top: 10px;
  color: #6c757d;
  font-size: 12px;
}

.image-label {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 10px;
}

.current-output-image {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.current-output-image .image-label {
  font-size: 14px;
  color: #495057;
  margin-bottom: 10px;
}

.current-output-image .preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.current-output-image .form-hint {
  display: block;
  margin-top: 10px;
  color: #6c757d;
  font-size: 12px;
}

/* 复选框样式 */
.checkbox-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 0;
}

.checkbox-wrapper input[type="checkbox"] {
  width: 20px;
  height: 20px;
  cursor: pointer;
  margin: 0;
}

.checkbox-label {
  cursor: pointer;
  font-weight: 500;
  color: #2c3e50;
  margin: 0;
  user-select: none;
}

/* 输出格式选择器样式 */
.output-type-options {
  display: flex;
  gap: 20px;
  margin-bottom: 12px;
  padding: 10px 0;
}

.type-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.type-option input[type="radio"] {
  margin: 0;
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.type-option label {
  cursor: pointer;
  font-weight: 500;
  color: #2c3e50;
  margin: 0;
  user-select: none;
}

.output-section {
  margin-top: 8px;
}

.output-section textarea {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 0.95em;
  transition: all 0.3s ease;
  background: white;
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

.output-section textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 输出格式图片上传区域样式 */
.output-file-upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
}

.output-file-upload-area:hover {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.05);
}

.upload-placeholder-small {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.upload-placeholder-small i {
  font-size: 32px;
  color: #bdc3c7;
}

.upload-placeholder-small p {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.upload-placeholder-small small {
  color: #95a5a6;
  font-size: 12px;
}

.uploaded-image-preview {
  position: relative;
  display: inline-block;
}

.uploaded-image-preview img {
  max-width: 300px;
  max-height: 200px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.remove-image-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.remove-image-btn:hover {
  background: #c0392b;
  transform: scale(1.1);
}

.remove-image-btn i {
  font-size: 14px;
}

/* 测试用例样式 */
.test-cases-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.test-cases-header label {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.add-test-case-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.add-test-case-btn:hover {
  background: linear-gradient(135deg, #388e3c, #2e7d32);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.4);
}

.test-cases-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.no-test-cases {
  text-align: center;
  padding: 40px 20px;
  color: #7f8c8d;
  background: #f8f9fa;
  border-radius: 12px;
  border: 2px dashed #dee2e6;
}

.no-test-cases i {
  font-size: 32px;
  margin-bottom: 10px;
  color: #bdc3c7;
}

.no-test-cases p {
  margin: 0;
  font-size: 14px;
}

.test-case-item {
  background: white;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.test-case-item:hover {
  border-color: #667eea;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
}

.test-case-header {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.test-case-number {
  font-size: 16px;
  font-weight: 600;
}

.remove-test-case-btn {
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 4px;
}

.remove-test-case-btn:hover {
  background: rgba(231, 76, 60, 0.8);
  border-color: rgba(231, 76, 60, 0.8);
}

.test-case-content {
  padding: 20px;
}

.format-section {
  margin-bottom: 20px;
}

.format-section > label {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #495057;
  margin-bottom: 10px;
}

.test-case-format {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 13px;
  transition: all 0.3s ease;
  background: #fff9e6;
  resize: vertical;
  min-height: 60px;
}

.test-case-format:focus {
  outline: none;
  border-color: #ffc107;
  box-shadow: 0 0 0 3px rgba(255, 193, 7, 0.1);
  background: white;
}

/* 输出格式类型选择器 */
.output-type-selector {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #555;
}

.radio-label input[type="radio"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.radio-label span {
  user-select: none;
}

/* 测试用例文件上传区域 */
.test-case-file-upload-area {
  border: 2px dashed #d0d0d0;
  border-radius: 12px;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
  min-height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.test-case-file-upload-area:hover {
  border-color: #667eea;
  background: #f5f7ff;
}

/* 上传占位符 */
.upload-placeholder-small {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  color: #999;
}

.upload-placeholder-small i {
  font-size: 40px;
  color: #d0d0d0;
}

.upload-placeholder-small p {
  margin: 0;
  font-size: 15px;
  font-weight: 500;
  color: #666;
}

.upload-placeholder-small small {
  font-size: 12px;
  color: #999;
}

/* 文件信息显示 */
.file-info-small {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #4CAF50;
  font-size: 14px;
  font-weight: 500;
}

.file-info-small i {
  font-size: 20px;
}

.clear-btn-small {
  background: #f44336;
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  margin-left: auto;
}

.clear-btn-small:hover {
  background: #d32f2f;
  transform: scale(1.1);
}

.clear-btn-small i {
  font-size: 12px;
}

.uploading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  color: #667eea;
}

.uploading-state i {
  font-size: 24px;
}

.uploading-state p {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

.upload-success-hint {
  margin-top: 10px;
  padding: 8px 12px;
  background: #e8f5e9;
  color: #4CAF50;
  border-radius: 6px;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.upload-success-hint i {
  font-size: 14px;
}

/* 当前输出格式图片预览 */
.current-output-image {
  margin-bottom: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px solid #e9ecef;
}

.current-output-image .image-label {
  font-size: 13px;
  color: #666;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.preview-image-small {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: block;
  margin: 0 auto;
}

/* 🔥 当前题目描述图片预览 */
.current-describe-image {
  margin-bottom: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px solid #e9ecef;
}

.current-describe-image .image-label {
  font-size: 13px;
  color: #666;
  margin: 0 0 10px 0;
  font-weight: 600;
}

/* 当前测试用例图片预览 */
.current-test-case-image {
  margin-bottom: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px solid #e9ecef;
}

.current-test-case-image .image-label {
  font-size: 13px;
  color: #666;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.image-preview-container {
  position: relative;
  text-align: center;
}

.preview-image-medium {
  max-width: 100%;
  max-height: 250px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  margin-bottom: 10px;
}

.change-image-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.change-image-btn:hover {
  background: linear-gradient(135deg, #764ba2, #667eea);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.current-test-case-image .form-hint {
  display: block;
  margin-top: 8px;
  font-size: 12px;
  color: #7f8c8d;
  font-style: italic;
}
</style>    